﻿/*
=======================================================
    Permission【权限】
=======================================================
*/

namespace Services
{
    public interface IPermissionRepository : IRepository<Permission>
    {
        List<int> GetLoginUserPermissionIDs();
        List<Permission> GetTreePermissionByRegulator();
        bool CurrentUserHasPermission(Permission_PerID permission_perID);
    }


    public class PermissionRepository : BaseRepository<Permission>, IPermissionRepository
    {
        public PermissionRepository(ISqlSugarClient dB, ICurrentUser currentUser, IQuery<Permission> query)
            : base(dB, currentUser, query)
        {
        }

        #region 得到当前登录用户所拥有的权限，给Me对象用  GetLoginUserPermissionIDs
        public List<int> GetLoginUserPermissionIDs()
        {
            List<int> ids = new List<int>();

            if (_currentUser.CurrentUserInfo.LoginUserType == LoginUserType.集团)
            {
                var userRoles = _DB.Queryable<UserRole>().Where(x => x.UserID == _currentUser.CurrentUserInfo.UserID).ToList();
                var roleIDs = userRoles.Select(x => x.RoleID).Distinct().ToList();

                var rolePermissions = _DB.Queryable<RolePermission>().Where(x => roleIDs.Contains(x.RoleID)).ToList();
                var permissionIDs = rolePermissions.Select(x => x.PermissionID).Distinct().ToList();

                return permissionIDs;
            }
            else if (_currentUser.CurrentUserInfo.LoginUserType == LoginUserType.监管部门)
            {
                var regulatorPermissions = _DB.Queryable<RegulatorPermission>().Where(x => x.RegulatorID == _currentUser.CurrentUserInfo.LoginTypeID).ToList();

                var permissionIDs = regulatorPermissions.Select(x => x.PermissionID).Distinct().ToList();

                return permissionIDs;
            }
            else
            {
                return ids;
            }
        }
        #endregion

        #region 获取所有监管部门权限的树形结构数据  GetAllRegultorPermission
        public List<Permission> GetTreePermissionByRegulator()
        {
            return _query.GetQueryable().Where(x => x.IsUseRegulator == true).ToList();
        }
        #endregion

        #region 判断当前集团用户是否有哪种权限
        public bool CurrentUserHasPermission(Permission_PerID permission_perID)
        {
            if (_currentUser.CurrentUserInfo.LoginUserType == LoginUserType.集团)
            {
                var roleIDs = _DB.Queryable<UserRole>().Where(x => x.UserID == _currentUser.CurrentUserInfo.UserID).Select(x => x.RoleID).ToList();
                var permissionIDs = _DB.Queryable<RolePermission>().Where(x => roleIDs.Contains(x.RoleID)).Select(x => x.PermissionID).ToList();
                var entity = _DB.Queryable<Permission>().Where(x => permissionIDs.Contains(x.PermissionID) && x.PerID == (int)permission_perID).First();
                return entity != null;
            }

            return false;
        }
        #endregion
    }
}
